<script setup>
import { Edit, Plus, Delete, Download, ZoomIn } from "@element-plus/icons-vue";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";

import { onMounted, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCategoryAPI } from "@/api/category";
import { addArticleAPI, deleteArticleAPI, getArticlesAPI, updateArticleAPI } from "@/api/article";
import { useUserStore } from "@/stores/useUserStore";

// 创建实例
const userStore = useUserStore();

//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(10); //总条数
const pageSize = ref(3); //每页条数
//用户搜索时选中的分类id
const categoryId = ref();
//用户搜索时选中的发布状态
const state = ref();

//当每页条数发生了变化，调用此函数
const onSizeChange = size => {
  pageSize.value = size;
  getArticles();
};
//当前页码发生变化，调用此函数
const onCurrentChange = num => {
  pageNum.value = num;
  getArticles();
};
// 获取当前账户分类数据
const categorys = ref();
const getCategorys = async () => {
  const res = await getCategoryAPI(userStore.account.id);
  if (res.code === 0) return (categorys.value = res.data);
  return ElMessage({ type: "error", message: res.message });
};

// 获取文章列表
//文章列表数据模型
const articles = ref();
const getArticles = async () => {
  const res = await getArticlesAPI(pageNum.value, pageSize.value, categoryId.value, state.value);
  if (res.code === 0) {
    articles.value = res.data.records;
    total.value = res.data.total;
    getIdName();
    return;
  }
  return ElMessage({ type: "error", message: res.message });
};
// 重置搜索词
const resetSearch = () => {
  categoryId.value = "";
  state.value = "";
  getArticles();
};

// 删除文章
const deleteArticle = row => {
  ElMessageBox.confirm("你确认删除该文章吗？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //用户点击了确认
      const res = await deleteArticleAPI(row.id);
      if (res.code === 0) {
        ElMessage({ type: "success", message: "删除成功" });
        return getArticles();
      }
      return ElMessage({ type: "error", message: res.message });
    })
    .catch(() => {
      //用户点击了取消
      ElMessage({ message: "已取消删除" });
    });
};

//控制抽屉是否显示
const visibleDrawer = ref(false);
//添加表单数据模型
const articleModel = ref({ id: "", title: "", categoryId: "", coverImg: "", content: "", state: "" });

const rules = ref({
  title: [
    { required: true, message: "请输入文章标题", trigger: "blur" },
    {
      pattern: /^\S{1,100}$/,
      message: "文章标题不能有空字符",
      trigger: "blur",
    },
  ],
  categoryId: [{ required: true, message: "请选择文章分类", trigger: "blur" }],
  coverImg: [{ required: true, message: "请上传封面图片", trigger: "blur" }],
  content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
});
// 新增文章
const formRef = ref();
const submitForm = async (formEl, state) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      articleModel.value.state = state;
      let res;
      if (articleModel.value.id) {
        res = await updateArticleAPI(articleModel.value);
      } else {
        res = await addArticleAPI(articleModel.value);
      }
      if (res.code === 0) {
        ElMessage({ type: "success", message: articleModel.value.id ? "修改成功" : "添加成功" });
        visibleDrawer.value = false;
        clearArticle();
        return getArticles();
      }
      return ElMessage({ type: "error", message: res.message });
    } else {
      for (const key in fields) {
        ElMessage({ type: "error", message: fields[key][0].message });
      }
    }
  });
};

// 全屏展示文章封面
const dialogVisible = ref(false);
// 上传结束禁止上传
const isEndUpload = ref(false);
const onSuccess = res => {
  articleModel.value.coverImg = res.data;
  isEndUpload.value = true;
};
// 判断是否放弃更改
const handleClose = done => {
  if (
    !articleModel.value.title &&
    !articleModel.value.content &&
    !articleModel.value.coverImg &&
    !articleModel.value.categoryId
  )
    return (visibleDrawer.value = false);
  const str = articleModel.value.id ? "修改" : "添加";
  ElMessageBox.confirm(`是否放弃当前${str}?`)
    .then(() => {
      done();
      getArticles();
      clearArticle();
      return ElMessage({ type: "info", message: `已放弃${str}` });
    })
    .catch(() => {});
};

const clearArticle = () => {
  articleModel.value.id = "";
  articleModel.value.title = "";
  articleModel.value.content = "";
  articleModel.value.categoryId = "";
  articleModel.value.coverImg = "";
  articleModel.value.state = "";
};
// 通过watch监听回显
const quill = ref();
watch(
  visibleDrawer,
  () => {
    if (!articleModel.value.id && quill.value !== undefined) quill.value.setHTML("");
  },
  { deep: true }
);
const getIdName = () =>
  articles.value.forEach(arr =>
    categorys.value.forEach(arrs => (arr.categoryId === arrs.id ? (arr.categoryName = arrs.categoryName) : ""))
  );
onMounted(() => {
  getArticles();
  getCategorys();
});
</script>
<template>
  <el-card class="page-container" v-if="articles || categorys">
    <template #header>
      <div class="header">
        <span>文章管理</span>
        <div class="extra">
          <el-button type="primary" @click="clearArticle(), (visibleDrawer = true), (isEndUpload = false)">
            添加文章
          </el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="文章分类：">
        <el-select placeholder="请选择" v-model="categoryId">
          <el-option label="全部" value="0"></el-option>
          <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="全部" value="0"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
          <el-option label="已发布" value="已发布"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getArticles">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%">
      <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="发表时间" prop="createTime"></el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="(isEndUpload = true), (visibleDrawer = true), (articleModel = row)"
          ></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <!-- 抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    :title="articleModel.id ? '修改文章' : '添加文章'"
    direction="rtl"
    size="50%"
    :before-close="handleClose"
  >
    <!-- 添加文章表单 -->
    <el-form :model="articleModel" label-width="100px" :rules="rules" ref="formRef">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="articleModel.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="categoryId">
        <el-select placeholder="请选择文章分类" v-model="articleModel.categoryId">
          <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章封面" :class="{ 'el-bottom': isEndUpload }" prop="coverImg">
        <el-upload
          class="avatar-uploader"
          :auto-upload="true"
          :show-file-list="false"
          action="/api/upload"
          :headers="{ Authorization: userStore.token }"
          :on-success="onSuccess"
        >
          <div v-if="articleModel.coverImg" @click.stop="dialogVisible = !dialogVisible">
            <img :src="articleModel.coverImg" class="avatar" />
            <span class="el-img-icon" v-if="isEndUpload">
              <el-icon size="large"><zoom-in /></el-icon>
            </span>
          </div>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="isEndUpload">
        <el-button size="small" @click="(isEndUpload = false), (articleModel.coverImg = '')">重新上传封面</el-button>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="articleModel.content"
            contentType="html"
            ref="quill"
          ></quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef, '已发布')">发布</el-button>
        <el-button type="info" @click="submitForm(formRef, '草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <el-dialog v-model="dialogVisible" title="文章封面" width="33%" align-center>
    <img class="cover-img" :src="articleModel.coverImg" alt="文章封面" />
  </el-dialog>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      position: relative;
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.cover-img {
  width: 100%;
  height: 100%;
}
.el-bottom {
  margin-bottom: 10px;
}
.el-img-icon {
  position: absolute;
  left: 5px;
  bottom: -5px;
}
</style>
